import {DataTypes, Model, Sequelize, Op} from 'sequelize';

const sequelize = new Sequelize('tank_im', 'root', '123456', {
    host: 'localhost',
    dialect: 'mysql',
    logging: console.log,
});

class User extends Model {
}

async function createTables() {
    User.init(
        {
            id: {
                type: DataTypes.INTEGER,
                allowNull: false,
                autoIncrement: true,
                primaryKey: true,
                comment: '用户id',
            },
            firstName: {
                type: DataTypes.STRING,
                field: 'first_name',
            },
            lastName: {
                type: DataTypes.STRING,
                field: 'last_name',
            },
            createTime: {
                type: DataTypes.DATE,
                field: 'create_time',
                defaultValue: DataTypes.NOW,
            },
            updateTime: {
                type: DataTypes.DATE,
                field: 'update_time',
                defaultValue: DataTypes.NOW,
            },
        },
        {
            sequelize,
            modelName: 'User',
            freezeTableName: true,
            tableName: 'user',
            timestamps: false,
            createdAt: false,
            updatedAt: false,
            deletedAt: false,
        }
    );

    await User.sync({ alter: true });
}

async function connect() {
    try {
        await sequelize.authenticate();
        console.log('mysql 连接成功');

        await createTables();
        console.log('创建 User 数据表完成');

        const user = User.build({
            firstName: randomString(),
            lastName: randomString(),
        });
        await user.save();
        console.log(user.toJSON());
        console.log('保存 user 数据成功');

        const userList = await User.findAll({
            attributes: ['id', 'first_name', 'last_name'],
            where: {
                id: {
                    [Op.gte]: 14,
                }
            },
            limit: 3,
            raw: true,
        });
        console.log(userList);
        console.log('查询 user 数据成功');

        await sequelize.close();
        console.log('mysql 连接关闭');
    } catch (error) {
        console.error('mysql 连接失败:', error);
    }
}

connect();

function randomString(maxLength = 16): string {
    let str = '';
    while (str.length <= maxLength) {
        str += Math.random().toString(32).substr(2).toUpperCase();
    }
    return str;
}

